<template>
    <div class="run_away_container">
        <div class="loss-title">
            <img class="loss-title-icon" src="@/assets/customer/warn.png" alt="" />
            <div class="loss-title-text">
                流失客户列表展示所有已流失的企微客户，客户删除最后一个可联系员工或最后一个可联系员工删除客户均记为已流失客户。你也可以在<span
                    @click="onDeletrecord"
                    >删人记录</span
                >页面查看历史删除记录。
            </div>
        </div>
        <div class="run_away_container_bottom">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                select-all-group
                select-all-radio
                :option="tableOption"
                :fetch-params="state.searchParams"
                :row-key="getRowKey"
                :fetch-api="fetchApi()"
                @select="onSelect"
                @select-all="onSelectAll"
                @selectAllTotal="selectAllTotal"
                @select-all-change="onSelectAllChange">
                <template #headerOperate>
                    <el-button v-auth="'EXPORT_CUSTOMER'" :disabled="exportDisabled" type="primary" @click="exportCus">
                        导出客户
                    </el-button>
                </template>
            </ZwTable>
        </div>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_MANAGE_RUNAWAY' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import { QuestionFilled } from '@element-plus/icons-vue';
import { getCusLossList, exportLostList } from '@/api/customerCenter';
import { ref, reactive, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { defaultTime } from '@/utils/utils';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const router = useRouter();
const checkList = ref([]);
const defaultParams = {
    add_time: [],
    lost_time: [],
    work_user_list: [],
    cust_info: ''
};

const tableRef = ref<HTMLElement | any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const selectTableTotal = ref<number>(0);

const exclude_ids = ref([]);

const exportDisabled = computed(() => {
    return !selectTableTotal.value;
});

const getRowKey = (row: any) => {
    return row.id;
};
let pickDay = '';
let pickDay2 = '';
const searchOption = computed(() => {
    return [
        {
            label: '客户信息',
            name: 'cust_info',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号 | 姓名搜索'
        },
        {
            label: '归属员工',
            name: 'work_user_list',
            value: [],
            type: 'select',
            placeholder: '请选择归属员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '添加时间',
            name: 'add_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            change: (val: any) => {
                if (!val) {
                    pickDay = '';
                    return;
                }
            },
            calendarChange: (time: any) => {
                const [pointDay] = time;
                pickDay = pointDay;
            },
            disabledDate: (time: any) => {
                if (!pickDay) {
                    return time.getTime() > Date.now();
                }
                const con1 = new Date(pickDay).getTime() - 364 * 24 * 60 * 60 * 1000;
                const con2 = new Date(pickDay).getTime() + 364 * 24 * 60 * 60 * 1000;
                const con3 = time.getTime() > Date.now();
                return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
            }
        },
        {
            label: '流失时间',
            name: 'lost_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            change: (val: any) => {
                if (!val) {
                    pickDay2 = '';
                    return;
                }
            },
            calendarChange: (time: any) => {
                if (!time) {
                    pickDay2 = '';
                    return;
                }
                const [pointDay] = time;
                pickDay2 = pointDay;
            },
            disabledDate: (time: any) => {
                if (!pickDay2) {
                    return time.getTime() > Date.now();
                }
                const con1 = new Date(pickDay2).getTime() - 364 * 24 * 60 * 60 * 1000;
                const con2 = new Date(pickDay2).getTime() + 364 * 24 * 60 * 60 * 1000;
                const con3 = time.getTime() > Date.now();
                return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
            }
        }
    ];
});
const search = (v: any) => {
    currentParams.value = v;
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
const reset = (v: any) => {
    pickDay = '';
    pickDay2 = '';
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    state.searchParams = { ...deepCopy(defaultParams) };
    currentParams.value = null;
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: '客户信息',
        label: '客户信息',
        width: 280,
        render({ row }: any) {
            return (
                <div class="cusInfo">
                    <el-image
                        src={row.avatar || 'https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png'}
                        fit="cover"
                        class="avatar">
                        {{
                            errpr: () => (
                                <div class="image-slot">
                                    <el-icon>
                                        <icon-picture />
                                    </el-icon>
                                </div>
                            )
                        }}
                    </el-image>
                    <div class="name">{row.name}</div>
                    <div class="sex">
                        {row.sex === 0 ? (
                            <img src="/static/customer/sex_0.png" />
                        ) : row.sex === 1 ? (
                            <img src="/static/customer/sex_1.png" />
                        ) : (
                            <img src="/static/customer/sex_2.png" />
                        )}
                    </div>
                </div>
            );
        }
    },
    {
        label: '手机号',
        width: 150,
        render({ row }: any) {
            return row.mobile || '-';
        }
    },
    {
        prop: 'tag_info',
        label: '客户标签',
        minWidth: 200,
        isTag: true
    },
    {
        prop: 'add_time',
        label: '添加时间',
        width: 200,
        renderHeader: () => {
            return (
                <div class="label_box">
                    <span>添加时间</span>
                    <el-tooltip placement="top" effect="dark" content="客户首次添加员工企业微信的时间。">
                        <el-icon>
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </div>
            );
        }
    },
    {
        prop: 'lost_time',
        label: '流失时间',
        width: 200,
        renderHeader: () => {
            const defaultContent = () => (
                <div style="width: 300px;">客户删除最后一个可联系员工的时间/最后一个可联系员工删除客户的时间。</div>
            );
            return (
                <div class="label_box">
                    <span>流失时间</span>
                    <el-tooltip placement="top" effect="dark" vSlots={{ content: defaultContent }}>
                        <el-icon>
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </div>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 110,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '详情',
                click: (row: any) => {
                    router.push(`/customer/manage/list/detail?id=${row.id}&type=${row.type}`);
                }
            }
        ]
    }
];
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return getCusLossList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 当页全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};

/**
 * 全部全选
 */

const onSelectAllChange = (val: any) => {
    exclude_ids.value = val;
};

/**
 * 选中的数据数量
 * @param res
 */
const selectAllTotal = (value: any) => {
    selectTableTotal.value = value;
};

// 导出客户
const exportCus = async (e: any) => {
    const params = {
        ...state.searchParams,
        select_type: tableRef.value?.getIsSelectAll() ? 2 : 1,
        cust_ids: tableRef.value?.getIsSelectAll() ? exclude_ids.value : checkList.value
    };
    const res = await exportLostList(params);
    parabolaAnimation(e);
    ShowTaskMessage('批量导出异步任务创建成功');
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    if (res.file_url) {
        // 这里之前有跳转的判断，此次异步任务并未涉及到。
        window.location = res.file_url;
    }
};

/**
 * 调转页面到删人记录
 */
const onDeletrecord = () => {
    router.push('/employee/staffsupervision/deletrecord');
};

onActivated((val: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
});
</script>

<style lang="scss" scoped>
.run_away_container {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .run_away_container_bottom {
        flex: 1;
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}

.loss-title {
    margin: 0 0 16px;
    display: flex;
    align-items: center;
    background: #fffbe6;
    border-radius: 2px;
    border: 1px solid #ffe58f;

    .loss-title-icon {
        margin-left: 17px;
        width: 14px;
        height: 14px;
    }

    .loss-title-text {
        padding: 9px 7px;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: rgb(0 0 0 / 65%);
        line-height: 22px;

        span {
            color: #ff6b00;
            cursor: pointer;
        }
    }
}

.layout {
    .container {
        display: flex;

        .container_right {
            flex: 1;
            padding: 20px;
            box-sizing: border-box;
            background: #fff;
            border: 1px solid #eaeaea;
            overflow: hidden;
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

:deep(.cusInfo) {
    display: flex;
    align-items: center;

    .avatar {
        width: 36px;
        height: 36px;

        .image-slot {
            .el-icon {
                font-size: 36px;
            }
        }
    }

    .name {
        margin: 0 10px;
    }

    .sex {
        width: 18px;
        height: 18px;

        img {
            width: 100%;
            height: 100%;
        }
    }
}

.time {
    line-height: 40px;
    font-size: 14px;
    font-family: STHeitiSC-Light, STHeitiSC;
    font-weight: 300;
    color: #33302d;
}

:deep(.tag_box) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.label_box) {
    display: flex;
    align-items: center;

    span {
        padding-right: 12px;
    }
}
</style>
